<?php

namespace app\api\controller;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Dysmsapi\Dysmsapi;
use app\api\model\Article;
use app\api\model\Category;
use app\api\model\Page;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Sms as Smslib;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Version;
use OSS\OssClient;
use think\captcha\Captcha;
use think\Config;
use think\Hook;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['select_list','article','article_detail','Sms_code','page','config','init', 'captcha','upload'];
    protected $noNeedRight = '*';

    /**
     * 下拉数据
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function select_list(){
        $param = request()->param();
        $Category = new Category();
        $where['type']=$param['type'];
        $where['status']="normal";
        $list=$Category->where($where)->field('id,name')->order('weigh desc')->select();
        foreach ($list as $k=>$vo){
            $list[$k]['text']=$vo['name'];
            $list[$k]['value']=$vo['name'];
        }
        $this->success('',$list);

    }
    /**
     * 文章列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function article(){
        $param = request()->param();
        $Article = new Article();
        $where['category_id']=$param['category_id'];
        $list=$Article->where($where)->field('*')->order('weigh desc')->select();
        $this->success('',$list);
    }
    public function article_detail(){
        $param = request()->param();
        $Article = new Article();
        $find=$Article->get($param['id']);
        $this->success('',$find);
    }
    /**
     * 单页
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function page(){
        $param = request()->param();
        $Page = new Page();
        $where['category_id']=$param['category_id'];
        $find=$Page->where($where)->find();
        $this->success('',$find);
    }

    /**
     * 系统变量
     * @return void
     */
    public function config(){
        $data['content_phone']=$this->config_data('content_phone');
        $data['service_phone']=$this->config_data('service_phone');
        $data['banner_ad']=$this->config_data('banner_ad');
        $data['share']=$this->config_data('share');
        $data['sign_in']=$this->config_data('sign_in');
        $this->success('',$data);
    }

    /**
     * 发送验证码
     * @return void
     */
    public function Sms_code(){
        $param = request()->param();
        AlibabaCloud::accessKeyClient('LTAI5tS9MDkrFoYK1nFPUnTx', 'ktyT3MPKkdmy2nSbnU3fOhQMIoKlzb')
            ->regionId('cn-zhangjiakou')
            ->asDefaultClient()->options([
            ]);
        try {
            $rand=rand(1111,9999);
            $request = Dysmsapi::v20170525()->sendSms();
            $result = $request

                ->withPhoneNumbers($param['phone'])
                ->withSignName("房东驾到")
                ->withTemplateCode("SMS_281370087")
                ->withTemplateParam("{\"code\":\"".$rand."\"}")
                ->debug(false) // Enable the debug will output detailed information
                ->request();
//            dump($result);die;
//            print_r($result->toArray());die;
            Smslib::send($param['phone'], $rand);
            $this->success('成功');
        } catch (ClientException $exception) {
            echo $exception->getMessage() . PHP_EOL;
        } catch (ServerException $exception) {
            echo $exception->getMessage() . PHP_EOL;
            echo $exception->getErrorCode() . PHP_EOL;
            echo $exception->getRequestId() . PHP_EOL;
            echo $exception->getErrorMessage() . PHP_EOL;
        }

    }
    public function Alibaba_Sms($phone,$code,$param="")
    {
        AlibabaCloud::accessKeyClient('LTAI5tGh7krv4q2UqoxEtXFh', 'AB65azjoYQNx3EnkLZjxeyj49OFBR6')
            ->regionId('cn-zhangjiakou')
            ->asDefaultClient()->options([
            ]);
        try {
            $request = Dysmsapi::v20170525()->sendSms();
            $result = $request
                ->withPhoneNumbers($phone)
                ->withSignName("鑫励诚")
                ->withTemplateCode($code)
                ->withTemplateParam($param)
                ->debug(false) // Enable the debug will output detailed information
                ->request();
            return $result;
        } catch (ClientException $exception) {
            return "失败";
        } catch (ServerException $exception) {
            return "失败";
        }
    }
    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            $upload = new Upload($file);
            $attachment = $upload->upload();
            $object = substr($attachment->url,1);
            $luj=dirname(dirname(dirname(dirname(__FILE__))))."/public";
            $filePath =$luj.$attachment->url;
            $config = get_addon_config('alioss');
            try{
                $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

                $ossClient->uploadFile($config['bucket'], $object, $filePath);
            } catch(OssException $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                return;
            }
//            try {
//                $upload = new Upload($file);
//                $attachment = $upload->upload();
//            } catch (UploadException $e) {
//                $this->error($e->getMessage());
//            }

            $this->success('成功', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 验证码
     * @param $id
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }
}
